#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}

// 插入新行
void Widget::on_pushButton_addRow_clicked()
{
    // 获取当前选中的行号
    int currentRow = ui->tableWidget->currentRow();

    if (currentRow >= 0) {
        // 如果有选中行，则在选中位置插入新行
        ui->tableWidget->insertRow(currentRow);
    } else {
        // 如果没有选中行，则在尾部插入新行
        currentRow = ui->tableWidget->rowCount();
        ui->tableWidget->insertRow(currentRow);
    }

    // 获取 QLineEdit 中输入的数据
    QString input = ui->lineEdit_input->text();

    // 设置新行的行名
    QTableWidgetItem *headerItem = new QTableWidgetItem(input);
    ui->tableWidget->setVerticalHeaderItem(currentRow, headerItem);

    // 清空之前的选中状态
    ui->tableWidget->clearSelection();

    // 选中新插入的行
    ui->tableWidget->selectRow(currentRow);
}


void Widget::on_pushButton_deleteRow_clicked()
{
    // 获取选中行号
    int curRow = ui->tableWidget->currentRow();
    // 删除选中行
    ui->tableWidget->removeRow(curRow);
}

void Widget::on_pushButton_addCol_clicked()
{
    // 获取选中列号
    int currentCol = ui->tableWidget->currentColumn();
    if(currentCol >= 0){
        ui->tableWidget->insertColumn(currentCol); // 在当前列的后面插入新列
    }else{
        currentCol = ui->tableWidget->columnCount();
        ui->tableWidget->insertColumn(currentCol); // 在尾部插入新列
    }

    // 获取QLineEdit的数据
    QString input = ui->lineEdit_input->text();

    // 将数据作为列名
    QTableWidgetItem *headerItem = new QTableWidgetItem(input);
    ui->tableWidget->setHorizontalHeaderItem(currentCol, headerItem);

    // 清空之前的选中状态
    ui->tableWidget->clearSelection();

    // 选中新插入的列
    ui->tableWidget->selectColumn(currentCol);
}

void Widget::on_pushButton_deleteCol_clicked()
{
    int curCol = ui->tableWidget->currentColumn();
    ui->tableWidget->removeColumn(curCol);
}
